package com.ryan.notify.business;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;

import com.ryan.notify.ad.AdProcess;
import com.ryan.notify.ad.model.AdResult;
import com.ryan.util.LogUtil;

public class CheckPackage {

    private static final int CALLBACKNUM=1;
    private static final int CALLBACKPROCESS=1;
    private boolean isCancel;
    
    public void cancel(){
        isCancel = true;
    }
    
    public static interface CheckCallback{
        void callback(List<AdResult> list);
        void processState(int max,int process);
        void processPkg(String pkg);
    }
    
    public List<AdResult> check(Context ctx,CheckCallback callback){
        List<String> pkgList =  getLaunchPkg(ctx);
        List<AdResult> checkResult = new ArrayList<AdResult>();
        int i = 0;
        int j = 0;
        List<AdResult> tmp = new ArrayList<AdResult>();
        for (String pkg : pkgList) {
            if(isCancel){
                return null;
            }
            AdResult pkgResult = AdProcess.getInstance().check(ctx, pkg);
            if(pkgResult.isAd()){
                checkResult.add(pkgResult);
                i++;
                if(callback!=null ){
                    tmp.add(pkgResult);
                    if(i%CALLBACKNUM==0){
                        callback.callback(tmp);
                        tmp.clear();
                    }
                }
            }
            j++;
            if(callback!=null ){
                if(j%CALLBACKPROCESS == 0){
                    callback.processState(pkgList.size(), j);
                }
                callback.processPkg(pkg);
            }
            LogUtil.v("CHECK","-------------do "+pkg);
        }
        if(callback!=null ){
            callback.callback(tmp);
            callback.processState(pkgList.size(), j);
        }
        LogUtil.v("CHECK", "find "+checkResult.size());
        return checkResult;
    }
    
    private List<String> getLaunchPkg(Context ctx){
        List<PackageInfo> list = ctx.getPackageManager().getInstalledPackages(0);
        List<String> rst = new ArrayList<String>();
        for (PackageInfo pkgInfo : list) {
            if ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0){
                rst.add(pkgInfo.packageName);
            }
        }
        return  rst;
    }
}
